<?php

require_once("includes/pagetop.php");

// These lines are mandatory.


//Code to detect mobile or pc by https://code.google.com/p/php-mobile-detect/wiki/SourceCode?tm=2
include 'includes/Mobile_Detect.php';
$detect = new Mobile_Detect;

$device="PC";

// 1. Check for mobile environment.

if ($detect->isMobile()) {
    $device="Mobile";
}

// 2. Check for tablet device.

if($detect->isTablet()){
    $device="Tab";
}

// 3. Check for any mobile device, excluding tablets.

if ($detect->isMobile() && !$detect->isTablet()) {
    $device="Mobile";
}

// 5. Redirect the user to your mobile version of the site.
if($detect->isMobile()){
    //header('http://m.yoursite.com', true, 301);
}

if(isset($_COOKIE['Allyfolio_User']))
{
    $_SESSION['Allyfolio_User_ID']=$_COOKIE['Allyfolio_User'];
    $_SESSION['Allyfolio_offset']=$_COOKIE['Allyfolio_offset'];
    redirect("home.php");
}

if(isset($_SESSION['Allyfolio_User_ID']))
{
    redirect("home.php");
}

if(!isset($_SESSION['login_attempt_emp']))
{
	$_SESSION['login_attempt_emp']=0;
}

$message="";

if(isset($resenduserphone) && $resenduserphone!="")
{
    $Alluserphone=$resenduserphone;
}



if(isset($Alluserphone) && $Alluserphone!="" && isset($action) && ($action=="forgot" || $action=="resend"))
{
    $Alluserphone=sanitize($Alluserphone);
    
    $userinfoqry="select User_ID,Email_ID,Full_Name from af_users where (Email_ID=:Email_ID or Mobile_Number=:Mobile_Number) ";
    $userinfo=$pdodbobj->fetch_array($pdodbobj->query($userinfoqry,array(":Email_ID"=>$Alluserphone,":Mobile_Number"=>$Alluserphone)));
        
    if(count($userinfo)>0)
    {
        require_once"includes/mailscript.php";
        
        $randomstring=random_string(20);
        
        $updatestring=array();
        $conditionarr=array();
        $conditionarr["User_ID"]=$userinfo[0]['User_ID'];
        $updatestring["Verify_Random_String"]=$randomstring;
        
        $emailid=$userinfo[0]['Email_ID'];
        if(isset($userinfo[0]['Secondary_Email_ID']) && trim($userinfo[0]['Secondary_Email_ID'])!='')
        {
            $emailid=$userinfo[0]['Secondary_Email_ID'];
        }
        
        $subject="Recover Password to Allyfolio Social Portal.";
        
        $bodymessage="
        <table cellspacing='2' cellpadding='2' width='100%'>
            <tr>
                <td>
                Hi ".$userinfo[0]['Full_Name'].",<br/><br></td>
            </tr>
            <tr>
                <td>
                    You have requested for changing your allyfolio account password. 
                 </td>
            </tr>
            <tr>
                <td>
                Please click on below link to reset your account password & continue with Allyfolio.<br>
                <a href='".WEBURL."resetpass.php?actcode=".$randomstring."' target='_blank'>".WEBURL."resetpass.php?actcode=".$randomstring."</a>
                </td>    
            </tr>
            <tr>
                <td>
                <br/>
                <br/>
                   Thanks,<br/>Allyfolio Support Team.
                </td>
            </tr>       
        </table>" ;  
        
        $pdodbobj->updateData("af_users",$updatestring,$conditionarr);
        if($pdodbobj->affectedrows>0)
        {
            if(sendMail($emailid,$subject,$bodymessage,$headers))
            {
                $passwordsendmsg="An email is sent to your registered Email id with reset password link. Please use that link to reset your password.";
            }
            else
            {
                $errormsg="There is an error in sending reset password email to your account.";
                
            }
            
        }
    }
    else
    {
        $errormsg="Please enter correct Email ID or Phone Number.";
    }
}

if(isset($Email_ID) && $Email_ID!="" && isset($Password) && $Password!=""  && isset($action) && $action=="signin")
{
    if(isset($_SESSION['captcha']) && $_SESSION['captcha']!="")
	{
		if($_POST['data']['captcha']==$_SESSION['captcha'])
		{
        }
        else
		{
			$_SESSION['login_attempt_emp']++;
			$message="Please enter correct captcha!";
		}
    }
	if($message=="")
    {	  
        $Email_ID=sanitize($Email_ID);
        $Password=sanitize($Password);
        $userinfoqry="select User_ID,Activation_Status from af_users where (Email_ID=:Email_ID or Mobile_Number=:Mobile_Number) and Password=:Pwd";
        $userinfo=$pdodbobj->fetch_array($pdodbobj->query($userinfoqry,array(":Email_ID"=>$Email_ID,":Mobile_Number"=>$Email_ID,":Pwd"=>md5($Password))));
        
        if(count($userinfo)>0)
        {
            if($userinfo[0]['Activation_Status']=="Pending")
            {
                $message="Please avtivate your account first using activation link, sent to your registered Email Id.";
            }
            else if($userinfo[0]['Activation_Status']=="Blocked")
            {
                $message="Your Account is blocked by our support staff/ admin, please contact to support team.";
            }
            else if($userinfo[0]['Activation_Status']=="Active")
            {
                $_SESSION['Allyfolio_User_ID']=$userinfo[0]['User_ID'];
		$_SESSION['Allyfolio_offset']=$_POST['timezone_hidden'];
                
                $insertarr=array("User_ID"=>$userinfo[0]['User_ID']);
                $insertarr["Status"]=$device." Login";
                $insertarr["logtime"]=time();
                
                $pdodbobj->insertData("af_user_loginout_log",$insertarr);
                
                $updatearr=array("Login_Status"=>$device." Login");
                $conditionarr=array("User_ID"=>$userinfo[0]['User_ID']);
                
                $pdodbobj->updateData("af_users",$updatearr,$conditionarr);
                
                if(isset($remember_me) && $remember_me==1)
                {
                    setcookie("Allyfolio_User",$userinfo[0]['User_ID'],time()+(30*24*60*60));
		    setcookie("Allyfolio_offset",$_POST['timezone_hidden'],time()+(30*24*60*60));
                    
                }
                unset($_SESSION['login_attempt_emp']);
                unset($_SESSION['captcha']);
                redirect("home.php");
            }
        }
        else
        {
            $_SESSION['login_attempt_emp']++;
            $message="Username or Password is not correct.";
        }
    }     
}

if($_SESSION['login_attempt_emp']>=5)
{
	$_SESSION['captcha']=random_string(6);
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AllyFolio | Login </title>
<link href="css/style.css" rel="stylesheet" type="text/css" media="all"  />

<script src="js/general.js"></script>

<link rel="stylesheet" href="alertify/themes/alertify.core.css" />
<link rel="stylesheet" href="alertify/themes/alertify.default.css" id="toggleCSS" />
<script src="alertify/lib/alertify.min.js"></script>	
<script src="js/jquery1.10.2.min.js"></script>

<script type="text/javascript" src="js/jquery_1.9.0_min.js"> </script>
<script type="text/javascript" src="js/script.js"></script>

</head>

<body>
<form class="signin" method="post">
	<div id="main_wrapper">
    <?php
    //$pageheading="Login";
    require_once("includes/header.php");
    ?>
    <!--=================Body Contain Start=======================-->
    <div class="wrapper row2" style="margin-top:30px;">
	<noscript>Enable your javascript to enjoy Allyfolio smoothly.</noscript>
                <?php
                if(isset($message) && $message!="")
                {
                ?>
                <div class="header errormsg" >
                    <?php echo $message; ?>
                    <br />
                    <br />
                </div>
                <?php
                }
                ?>
    	<div class="header">
    		<div class="front-signin js-front-signin">
                
                
                <div class="placeholding-input username">
                    
                    <label class="placeholder" for="signin-email" style="text-shadow: 0px 2px 5px #666">Email or Phone No</label>
                    <input class="text-input" type="text" name="Email_ID" id="username" style="margin-left:4px;"  />
                </div>
                
                <div class="remember-forgot">
                    <label class="remember">
                    <input type="checkbox" checked="checked" class="checkbox" name="remember_me" value="1" />
                    <span style="text-shadow: 0px 2px 5px #666">Keep me logged in</span>
                    </label>
                
                </div>
                
                <div class="clearfix"></div>
                
                <div class="placeholding-pwd">
                    <label class="placeholder" for="signin-password" style="text-shadow: 0px 2px 5px #666">Password</label>
                    <input class="text-input" type="password" name="Password" id="password" style="margin-left:4px;" />
                    
                </div>
                
                <div class="clearfix"></div>
                
                <?php
					if(isset($_SESSION['captcha']) && $_SESSION['captcha']!="")
					{
					?>
					<div class="input-prepend" style="width: 180px;">
						<table cellpadding="2" width="100%" border="0" cellspacing="2">
							<tr>
								<td width="">
                                    <img id="imgCaptcha" src="create_captcha.php" />
								</td>
								<td>
									<img src="images/refresh.png" onclick="change_captcha();" style="cursor:pointer">
								</td>
							</tr>
							<tr>
								<td colspan="2"><input type="text" class="text-input" tabindex="4" id="Captcha" name="data[captcha]" style="margin-left:4px;" /></td>
							</tr>
						</table>
						
					</div>
					<?php
					}
					?>
                 <div class="clearfix"></div>           
                <span class="separator"></span>
                <a class="forgot" href="#" onclick="return showhideforgot('forgot');" style="padding:4px; text-shadow: 0px 2px 5px #666">Forget Your Password?</a>
                
                
                <div class="clearfix"></div>
                <button class="submit" id="login" type="submit">Log in</button>
		<input type="hidden" name="timezone_hidden" id="timezone_hidden" />
                
                
            </div>
		</div>
    </div>
    
    <div class="clearfix"></div>
    <!--=================Body Contain end=======================-->
    </div>
    <div id="toPopup"> 
    	
        <div class="close" onclick="closePopup();"></div>
        <div id="popup_content" >  
            <div class="forgetPass">
            
              <h3>Forget Password</h3>
              <?php
            if(isset($errormsg) && $errormsg!="")
            {
                ?>
                <div class="errormsg" ><?php echo $errormsg; ?><br /><br /></div>
                <?php
            }
            ?>
                  <label>Enter your E-mail / User ID</label>
                  <input type="text" name="Alluserphone" id="forgotusername" placeholder="Enter your E-mail / User ID" /> 
                  <p>Your password will be sent to your E-mail & you can check 
                your password on your mail account. You may also contact to
                our help center for any issue.</p>
                
                <div class="btns"><input type="submit" value="Submit" id="forgotpassbtn" /> &nbsp; <input type="button" value="Cancel" class="simplebutton" onclick="return closePopup();" /></div>
              
              </div>        
        </div>
        <div id="fsentcontent" style="display: none;">  
            <div class="forgetPass">
              <h3>Forget Password</h3>
                <p>Your password has been sent to your E-mail & you can check 
            your password on your mail please. If your password not
            delivered on your mail you can resend again.</p>
            <input type="hidden" name="resenduserphone" value="<?php if(isset($Alluserphone)&& $Alluserphone!=""){ echo $Alluserphone; } ?>" />
            <div class="btns"><input type="submit" value="Resend"  id="resendpassbtn" /> &nbsp; <input type="button" value="Cancel" class="simplebutton" onclick="return closePopup();" /></div>
              
              </div>            
        </div>
        </div>
        	<div class="loader"></div>
   	<div id="backgroundPopup"></div>
    <input type="hidden" name="action" id="action" />
    </form>
<?php
    require_once("includes/footer.php");
?>

<script lang="javascript">
//<![CDATA[
    
    $("#login").click(validateUserInput);
    
    function validateUserInput()
    {
        
        if(trim(document.getElementById('username').value)=="")
        {
            alertify.alert("Please enter email id or mobileno.");
            document.getElementById('username').focus();
            return false;
        }
        else if(trim(document.getElementById('password').value)=="")
        {
            alertify.alert("Please enter password.");
            document.getElementById('password').focus();
            return false;
        }
        else
        {
            document.getElementById('action').value="signin";
            document.signin.submit();
        }
    }
    
    function change_captcha()
    {
    	var img = document.getElementById('imgCaptcha'); 
       //Change the image
        img.src = 'create_captcha.php?' + Math.random();
    }
    
    $("#forgotpassbtn").click(validateForgotPass);
    
    function validateForgotPass()
    {
        if(trim(document.getElementById('forgotusername').value)=="")
        {
            alertify.alert("Please enter either email id or phone number.");
            document.getElementById('forgotusername').focus();
            return false;
        }
        else
        {
            document.getElementById('action').value="forgot";
            return true;
        }
    }
    
    $("#resendpassbtn").click(validateResendPass);
    
    function validateResendPass()
    {
        
        document.getElementById('action').value="resend";
        return true;
        
    }
    
    function showhideforgot(action)
    {
        if(action=="forgot")
        {
            document.getElementById('popup_content').style.display='';
            document.getElementById('fsentcontent').style.display='none';
        }
        else
        {
            document.getElementById('popup_content').style.display='none';
            document.getElementById('fsentcontent').style.display='';
        }
        showpopup();
    }
    
    <?php
    if(isset($passwordsendmsg) && $passwordsendmsg!="")
    {
        ?>
        showhideforgot('resend');
        <?php
    }
    ?>
    
    <?php
    if(isset($errormsg) && $errormsg!="")
    {
        ?>
        showhideforgot('forgot');
        <?php
    }
    ?>
    
//]]>
var d = new Date()
document.getElementById("timezone_hidden").value = d.getTimezoneOffset(); 
</script>